package top.zhangjianyong.netty.bio;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    public static void main(String[] args) throws IOException {
        /*创建线程池*/

        ExecutorService threadPool = Executors.newCachedThreadPool();

        /*创建ServerSocket*/
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");
        while (true) {
            /*等待客户端连接*/
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            /*创建线程与之通讯*/
            threadPool.execute(() -> {
                handler(socket);
            });
        }
    }

    /*handler 客户端通讯*/
    public static void handler(Socket socket) {
        try {
            System.out.println("当前线程:"+Thread.currentThread().getId());
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            StringBuilder sb = new StringBuilder();

            while (true) {
                int read = inputStream.read(bytes);
                if (read != -1) {
                    String s = new String(bytes, 0, read);
                    System.out.println(s);
                    sb.append(s);
                    outputStream.write("ok".getBytes());
                    outputStream.flush();
                } else {
                    break;
                }
            }

            //System.out.println(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭socket连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
